
import 'package:ky_tool_plugin/config/ky_default_utils.dart';
import 'package:ky_tool_plugin/config/ky_project_configure.dart';
import 'package:ky_tool_plugin/tools/ky_log_utils.dart';

import 'dio_utils.dart';
import 'dart:convert' as convert;

typedef Success<T> = Function(T data);
typedef Fail = Function(int code,String msg);

class HttpUtils {


  //_request 请求
  static Future request<T> (
      Method method,
      String url,
      parameters, {
        required Success success,
        required Fail fail,
      }) async{

    parameters.forEach((key, value) {
      if (url.indexOf(key) != -1) {
        url = url.replaceAll(':$key', value.toString());
      }
    });

    await DioUtils().request(method, url, parameters, success: (result) {
      LogUtils.d("--------- response--url===$url ---------");
      LogUtils.d('result==========$result');

      Map <String,dynamic> resultMap;

      try{
        resultMap = convert.jsonDecode(result);
      } on FormatException {
        if (fail != null) {
          fail(9999,'数据解析失败');
        }
        return;
      } finally {

      }

      dynamic resultCode = resultMap['code'];
      LogUtils.d('resultCode===$resultCode');

        if (success != null) {
          success(resultMap);
        }
    }, fail: (code, msg) {
      if (fail != null) {
        fail(code,msg);
      }
    });
  }
}
